package com.filter;

import com.utils.DataConsts;
import com.utils.EncodingHttpServletRequest;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

//后缀名匹配
@WebFilter(urlPatterns = {"/*","*.html", "*.jsp", "*.js", "*.css", "*.do"})
//精确匹配
//@WebFilter(urlPatterns = {"/admin/admin1.html"})
public class Demo02Filter implements Filter {
    private static String encoding;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //1.从 配置文件、注解当中 拿到字符编码的信息
        encoding = filterConfig.getInitParameter("encoding");
        System.out.println("过滤器的别名：" + filterConfig.getFilterName());
        System.out.println("拿到ServletContext（域对象）：" + filterConfig.getServletContext());
        Enumeration<String> initParameterNames = filterConfig.getInitParameterNames();
        while (initParameterNames.hasMoreElements()) {
            System.out.println(initParameterNames.nextElement());
        }
        //2.如果在配置文件中没有配置字符编码 就使用默认编码
        if (encoding == null || encoding.isEmpty()) {
            encoding = DataConsts.DEFAULT_CHARSET;
        }
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        System.out.println("Demo02Filter doFilter");
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        if ("GET".equalsIgnoreCase(request.getMethod())) {
            EncodingHttpServletRequest wrapper = new EncodingHttpServletRequest(request, encoding);
            chain.doFilter(wrapper, response);
        } else {
            request.setCharacterEncoding(encoding);
            response.setContentType("text/html;charset=" + encoding);
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
